package cn.mrlong.basicframework.utils;

import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.util.Log;

import java.lang.reflect.Method;
import java.util.UUID;

import static android.text.TextUtils.isEmpty;

/**
 * Created by BINGO on 2018/08/01.
 */

public class DeviceIdUtil {

    public static String getDeviceId(Context context) {
        StringBuilder deviceId = new StringBuilder();
        // 渠道标志
        deviceId.append("a");
        try {

            //IMEI（imei）
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                return deviceId.append("id").append(getUUID(context)).toString();
            }
            String imei = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                imei = tm.getImei();
            } else {
                imei = tm.getDeviceId();
            }
            if (!isEmpty(imei)) {
                deviceId.append("imei");
                deviceId.append(imei);
                Log.e("getDeviceId : ", deviceId.toString());
                return deviceId.toString();
            }
            //序列号（sn）
            String sn = tm.getSimSerialNumber();
            if (!isEmpty(sn)) {
                deviceId.append("sn");
                deviceId.append(sn);
                Log.e("getDeviceId : ", deviceId.toString());
                return deviceId.toString();
            }
            //sn
            String serial = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {//9.0+
                serial = Build.getSerial();
            } else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {//8.0+
                serial = Build.SERIAL;
            } else {//8.0-
                Class<?> c = Class.forName("android.os.SystemProperties");
                Method get = c.getMethod("get", String.class);
                serial = (String) get.invoke(c, "ro.serialno");
            }
            if (null != serial) {
                deviceId.append("serial");
                deviceId.append(serial);
                return deviceId.toString();
            }
            //如果上面都没有， 则生成一个id：随机码
            String uuid = getUUID(context);
            if (!isEmpty(uuid)) {
                deviceId.append("id");
                deviceId.append(uuid);
                Log.e("getDeviceId : ", deviceId.toString());
                return deviceId.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            deviceId.append("id").append(getUUID(context));
        }
        Log.e("getDeviceId : ", deviceId.toString());
        return deviceId.toString();
    }

    private static String uuid;

    /**
     * 得到全局唯一UUID
     */
    private static String getUUID(Context context) {

        SharedPreferences mShare = getSysShare(context);
        if (mShare != null) {
            uuid = mShare.getString("uuid", "");
        }
        if (isEmpty(uuid)) {
            uuid = UUID.randomUUID().toString();
            saveSysMap(context, ANDROID_DEVICE_ID, "uuid", uuid);
        }
        Log.e(tag, "getUUID : " + uuid);
        return uuid;
    }

    private static void saveSysMap(Context context, String sysCacheMap, String keyName, String uuidVal) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(sysCacheMap, Context.MODE_PRIVATE);
        if (uuidVal instanceof String) {
            sharedPreferences.edit().putString(keyName, (String) uuidVal).commit();
        }
    }

    private static SharedPreferences getSysShare(Context context) {
        return context.getSharedPreferences("ANDROID_DEVICE_ID", Context.MODE_PRIVATE);
    }

    private static String tag = "android_device_id";
    private static String ANDROID_DEVICE_ID = "ANDROID_DEVICE_ID";
}
